// app/model/sales_order_item_model.js
'use strict';

module.exports = app => {
  const { STRING, INTEGER, DATE, DECIMAL } = app.Sequelize;

  const SalesOrderItem = app.model.define('sales_order_item', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    orderId: {
      type: INTEGER,
      allowNull: false,
      field: 'order_id'
    },
    productId: {
      type: INTEGER,
      allowNull: true,
      field: 'product_id'
    },
    productName: {
      type: STRING(100),
      allowNull: false,
      field: 'product_name'
    },
    specification: {
      type: STRING(100),
      allowNull: true
    },
    quantity: {
      type: INTEGER,
      allowNull: false
    },
    unit: {
      type: STRING(20),
      allowNull: true
    },
    unitPrice: {
      type: DECIMAL(15, 2),
      allowNull: false,
      field: 'unit_price'
    },
    amount: {
      type: DECIMAL(15, 2),
      allowNull: false
    },
    remark: {
      type: STRING(200),
      allowNull: true
    },
    createdAt: {
      type: DATE,
      field: 'created_at'
    },
    updatedAt: {
      type: DATE,
      field: 'updated_at'
    }
  }, {
    tableName: 'sales_order_items',
    timestamps: true
  });

  // 关联关系
  SalesOrderItem.associate = function() {
    // 与销售订单关联
    SalesOrderItem.belongsTo(app.model.SalesOrderModel, {
      foreignKey: 'orderId',
      as: 'order'
    });
    
    // 与产品关联（如果存在）
    SalesOrderItem.belongsTo(app.model.ProductModel, {
      foreignKey: 'productId',
      as: 'product'
    });
  };

  return SalesOrderItem;
};